import WebUploader from 'webuploader/dist/webuploader.js';
import PaBaseModel from '../../core/model/PaBaseModel.js';
import equipmentInspectionAdditionTpl from '../dialogs/equipmentInspectionAddition4Detail.html';

function equipmentInfoCtrl($scope, $http, ngDialog, fileUploaderService) {
  'ngInject';

  let _this = this;
  let id = $state.params.id;
  
  // 保存上传文件返回token
  this.acceptRecordToken = []; // 验收记录上传图片token

  this.equipmentInfo = {
    deviceName: '', // 设备名称
    innerNo: '', // 档案编号
    deviceModel: '', // 设备型号
    registrationNo: '', // 注册号
    license: '', // 拍照
    deviceLevel: '', // 设备等级
    operator: '', // 操作人员
    approachTime: '', // 进场时间
    exitTime: '', // 退场时间
    maintainSituation: '', // 维保情况
    isRented: '', // 是否租赁 0 否: 1 是
    fileBeans: [], // 检验记录图片
  }

  this.editableEquipmentInfo = new PaBaseModel(this.equipmentInfo);

  // 查询设备详细信息
  this.basedInformationQuery = () => {
    $http.get(`${SERVER_CONTEXT}/api/deviceinfo/queryDeviceDetail/${id}`)
      .then((resp) => {
        this.equipmentInfo = resp.data;
        if (!this.equipmentInfo.fileBeans) {
          this.equipmentInfo.fileBeans = [];
        }
        this.editableEquipmentInfo = new PaBaseModel(this.equipmentInfo);
      });
  };

  this.basedInformationQuery();

  // 更新设备信息请求
  this.updateEquipInfo = (reload) => {
    $http.patch(`${SERVER_CONTEXT}/api/deviceinfo/updateDeviceInfo`, _this.editableEquipmentInfo)
      .then((resp) => {
        _this.editableEquipmentInfo.$sync();
        if(reload) $state.reload();
        _this.editable = false;
      });
  }

  // 基本信息按钮时间
  this.baseInfoEventHandler = {
    // 切换编辑状态
    toggleEditable: () => {
      // 取消按钮
      if (this.editable) {
        this.editableEquipmentInfo.$reset();
      }
      this.editable = !this.editable;
    },

    // 获得头像图片
    getAvatarSrc: () => {
      if (_this.equipmentInfo && _this.equipmentInfo.fileBean && _this.equipmentInfo.fileBean.filePath) {
        let src = `${SERVER_IP}/${_this.equipmentInfo.fileBean.filePath}`;
        return src;
      } else {
        return require('../../../assets/images/' + 'timg.jpg');
      }
    },

    // 保存设备基本信息
    save: (param) => {
      // 修改表单是否提交过状态
      param.$submitted = true;

      // 表单校验
      if (param.$invalid) {
        return false;
      }
      // 把文件上传返回token传入this.userInfo
      let imageToken = '';
      if (this.editableEquipmentInfo.fileBean) {
        imageToken = this.editableEquipmentInfo.fileBean.id;
      } else {
        imageToken = '';
      }
      this.editableEquipmentInfo.image = imageToken;
      this.updateEquipInfo(true);
    },

    // 重置
    reset: () => {
      this.editableEquipmentInfo.$reset();
    }
  }

  /** 验收图片上传删除部分 */
  const FILE_NUM_LIMIT = 9;
  this.acceptanceEditable = false;
  this.cancelEditAcceptance = () => {
    this.editableEquipmentInfo.$reset();
  }
  this.toggleAcceptanceEditable = () => {
    if (this.acceptanceEditable) {
      this.cancelEditAcceptance();
    }
    this.acceptanceEditable = !this.acceptanceEditable;
  }

  this.saveAcceptanceImage = () => {
    this.editableEquipmentInfo.inspectionRecords =
      this.editableEquipmentInfo
                                .fileBeans
                                .filter(item => item.id)
                                .map(item => item.id).join(',');
    this.updateEquipInfo();
    this.acceptanceEditable = false;
  }
  // 获得验收图片路径
  this.getAcceptanceImgSrc = (imageFile) => {
    if (imageFile.filePath) {
      let src = `${SERVER_IP}/${imageFile.filePath}`;
      return src;
    } else if (imageFile.dataUrl) {
      return imageFile.dataUrl;
    }
  }

  // 删除文件
  this.deleteAcceptanceImage = (item) => {
    _this.fileList = _this.editableEquipmentInfo.fileBeans;    
    let index = _this.fileList.indexOf(item);
    if (index >= 0) {
      _this.fileList.splice(index, 1);
    }
    let fileId = item.webuploaderFileId;
    if (fileId) {
      _this.webuploader.removeFile(fileId);
    }
  }

  // 验证上传文件数量是否超过限制
  function beforeFileQueuedCB() {
    _this.fileList = _this.editableEquipmentInfo.fileBeans;
    // 如果传入的property是空则赋值为数组
    if (!_this.fileList) _this.fileList = [];

    if (_this.fileList.length >= FILE_NUM_LIMIT) {
      layer.alert(`最多可上传${FILE_NUM_LIMIT}个文件`);
      return false;
    }
  }

  // 验收文件加入队列回调函数
  function acceptanceFileQueuedCB(file) {
    let webuploader = this;

    // 创建缩略图
    webuploader.makeThumb(file, (error, src) => {
      $scope.$apply(() => {
        _this.activeAcceptanceFile = {
          fileName: file.name,
          dataUrl: src,
          webuploaderFileId: file.id,  // webuploader file 的id
        };
        _this.editableEquipmentInfo.fileBeans.push(_this.activeAcceptanceFile);
      });
    }, 100, 100); 
  }

  // 图片上传成功添加回调函数
  function acceptanceUploadSuccessCB(file, resp) {
    // this指向fileUploader
    let webuploader = this;
    
    // 保存返回信息token
    $scope.$apply(() => {
      _this.activeAcceptanceFile.id = resp.message;
    });
  } 

  // 文件上传失败回调函数
  this.errorUploadFileList = {};
  function acceptanceUploadErrorCB(file, reason) {
    _this.errorUploadFileList[file.id] = file;  
  }
  // 上传图片
  this.webuploader = fileUploaderService.initUploader({
    auto: true,
    server: `${SERVER_CONTEXT}/api/deviceinfo/uploadDeviceInfo`,
    pick: {
      id: '#acceptancePicker',
      multiple: false,
    },
    duplicate: false,
  }, acceptanceFileQueuedCB, acceptanceUploadSuccessCB, acceptanceUploadErrorCB);

  this.webuploader.on('beforeFileQueued', beforeFileQueuedCB);


  // 查询检测记录
  this.checkRecordList = [];
  this.queryCheckRecordData = () => {
    $http.post(`${SERVER_CONTEXT}/api/devicecheckrecord/queryCheckRecordList`, {"deviceId": id})
      .then((resp) => {
        this.checkRecordList = resp.data.data;
      });
  }
  this.queryCheckRecordData();

  // 获得图片路径
  this.getCheckRecordSrc = (file) => {
    if (file.filePath) {
      let src = `${SERVER_IP}/${file.filePath}`;
      return src;
    }
    return '';
  }

  // 新增检验记录
  this.addCheckRecord = function(){
    ngDialog.open({
      template: equipmentInspectionAdditionTpl,
      plain: true,
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'addTextCode',
      controller: function($http, $scope) {
        'ngInject';
        this.addItem = {
          deviceId: id,
          fileBeans: [],
          deviceInfoBean: {
            id: id,
          },
        };
        this.attachments = [];
        this.submit = (param) => {
          // 修改表单是否提交过状态
          param.$submitted = true;
          // 表单校验
          if (param.$invalid) {
            return false;
          } else if(param.checkTime.$viewValue < param.nextChecktime.$viewValue) {
            // accessory 属性用于接收附件token 多个附件以逗号分隔
            this.addItem.accessory = this.attachments.map(item => item.id).join(',');
            $http.post(`${SERVER_CONTEXT}/api/devicecheckrecord/insertCheckRecord`,
                this.addItem)
                .then((resp) => {
                  if (resp.data.success) {
                    layer.msg(resp.data.message);
                    _this.queryCheckRecordData();
                    $scope.closeThisDialog();
                  } else {
                    layer.alert(resp.data.message);
                  }
                });
              } else {
                layer.alert('检测时间应小于下次检测时间');
              }
          
        }
      },
    }); 
  }

  // 删除检验记录
  this.deleteCheckRecord = (id) => {
    let _this = this;
    $scope.modalTitle = '删除检测记录';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
    template: 'paConfirm',
    className: 'ngdialog-theme-default pa-confirm-theme',
    scope: $scope,
    }).
      then((value) => {
        $http.delete(`${SERVER_CONTEXT}/api/devicecheckrecord/deleteCheckRecord/${id}`)
              .then((resp) => {
                if (resp.data.success) {
                  layer.msg(resp.data.message);
                  _this.queryCheckRecordData();
                  // $scope.closeThisDialog();
                } else {
                  layer.alert(resp.data.message);
                }
              });
      }, (reason) => {});
  } 

  // 新增维保记录query data
  this.maintainRecordData = new PaBaseModel({
    deviceId: id, // 设备id
    maintainTime: '',  // 维保时间
    maintainContent: '', // 维保内容
    deviceInfoBean: {
      id: id,
    },
  });

  // 新增维保记录，出现form表单
  this.addMainRecord = () => {
    this.addRecord = !this.addRecord;
    this.maintainRecordData.$reset();
  }

  // 取消新增维保记录按钮
  this.cancelAddMaintainRecord = () => {
    this.addRecord = false;
    this.maintainRecordData.$reset();
  }

  // 新增一条维保记录
  this.addItemRecord = (param) => {
    // 修改表单是否提交过状态
    param.$submitted = true;
    // 表单校验
    if (param.$invalid) {
      return false;
    } else {
      $http.post(`${SERVER_CONTEXT}/api/devicemaintainrecord/insertMaintainRecord`,
        this.maintainRecordData)
        .then((resp) => {
          if (resp.data.success) {
            layer.msg(resp.data.message);
            $state.reload();
            this.queryMaintainList();
          } else {
            layer.alert(resp.data.message);
          }
        });
    }

  };

  // 查询设备维保记录
  this.maintainRecordList = [];
  this.editableMaintainRecordList = [];
  this.queryMaintainList = () => {
    $http.post(`${SERVER_CONTEXT}/api/devicemaintainrecord/selectMaintainRecordList`, {"deviceId": id})
      .then((resp) => {
        this.maintainRecordList = resp.data.data;
        this.maintainRecordList.forEach((item) => {
          this.editableMaintainRecordList.push(new PaBaseModel(item));
        });
      });
  }
  this.queryMaintainList();

  // 编辑维保记录
  this.editRecord = (item) => {
    item.record = true;
  }

  // 取消编辑维保记录
  this.cancelRecord = (item, $index) => {
    this.editableMaintainRecordList[$index].$reset();
    item.record = false;
  };

  // 删除维保记录
  this.recordDetete = (item) => {
    $scope.modalTitle = '删除信息';
    $scope.modalContent = '确认要删除此信息吗?';
    ngDialog.openConfirm({
      template: 'paConfirm',
      className: 'ngdialog-theme-default pa-confirm-theme',
      scope: $scope,
    })
      .then((value) => {
         $http({
           method: 'DELETE',
           url: `${SERVER_CONTEXT}/api/devicemaintainrecord/deleteMaintainRecord/${item.id}`
         })
           .then((resp) => {
             if (resp.data.success) {
              layer.msg('删除成功');
              this.queryMaintainList();
             }
           });
      }, (reason) => {});
  }

  // 保存编辑维保记录
  this.saveRecordItem = (item, $index) => {
    let queryData = this.editableMaintainRecordList[$index];
    $http.patch(`${SERVER_CONTEXT}/api/devicemaintainrecord/updateMaintainRecord`, queryData)
        .then((resp) => {
          if (resp.data.success) {
            this.queryMaintainList();
            layer.msg(resp.data.message);
          } else {
            layer.alert(resp.data.message);
          }
        });
    item.record = false;
  }
}

export default equipmentInfoCtrl;